import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View,Text} from '@tarojs/components'
import { Button,Field } from '@antmjs/vantui'
import { connect } from 'react-redux'
import List from './components/list';
import { LoadVarietyActionAsync} from '../../redux/action/VarietyAction';
import { ClearShoppingAction} from '../../redux/action/shoppingAction';
import { ChangeLoadingAction } from '../../redux/action/loadingAction';
import Loading from '../../components/Loading/index'
import http from '../../service/http'
import dev from '../../../config/dev';
import './index.less'

const isH5 = process.env.TARO_ENV === 'h5'

let dateTypeFormat = function(fmt, date) {
  let ret
  const opt = {
    'Y+': date.getFullYear().toString(), // 年
    'm+': (date.getMonth() + 1).toString(), // 月
    'd+': date.getDate().toString(), // 日
    'H+': date.getHours().toString(), // 时
    'M+': date.getMinutes().toString(), // 分
    'S+': date.getSeconds().toString() // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  }
  for (const k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt)
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
    }
  }
  return fmt
}

@connect(	state => ({
    varietyList:state.varietyList,
    shoppingCart:state.shoppingCart
	}),
	{LoadVarietyActionAsync,ClearShoppingAction}
)
class Index extends Component {
  state={
    num:null,
    remarks:'',
    tableNumId:0
  }

  // UNSAFE_componentWillMount () { console.log('UNSAFE_componentWillMount,组件还没挂载前');if(isH5){console.log('你当前环境为H5')} }

  // componentDidMount () { console.log('componentDidMount,组件挂载后');}

  // shouldComponentUpdate (nextProps,nextState) { console.log('shouldComponentUpdate,组件是否需要更新',nextProps,nextState);return true }

  // componentWillUnmount () { console.log('componentWillUnmount,组件卸载前') }

  // componentDidShow () { console.log('componentDidShow,组件显示后') }

  // componentDidHide () { console.log('componentDidHide,组件隐藏后') }

    // onLoad
  onLoad (options) {
    // scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    // const scene = decodeURIComponent(options.scene)
    console.log(this.props.shoppingCart)
    this.setState({num:options.num,tableNumId:options.tableNumId})
  }

  // onReady
  onReady () {}

  // 对应 onShow
  componentDidShow () {}

  // 对应 onHide
  componentDidHide () {}

  // 对应 onPullDownRefresh，除了 componentDidShow/componentDidHide 之外，
  // 所有页面生命周期函数名都与小程序相对应
  onPullDownRefresh () {}
  submitClick=()=>{
    let that=this
    Taro.showModal({
      title: '提示',
      content: '你确定要提交订单吗？',
      success: async function (res) {
        let openId=Taro.getStorageSync('openId')
        if (res.confirm) {
          let obj={
            tablenumId:parseInt(that.state.tableNumId),
            customId:openId,
            peopleNum:parseInt(that.state.num),
            money:(that.props.shoppingCart.money*100)/100,
            status:0,
            time: dateTypeFormat('YYYY-mm-dd HH:MM:SS',new Date()),
            remarks:that.state.remarks
          }
          // console.log(obj)
          try{
            Taro.showLoading({
              title: '加载中',
            })
            let response=await http.addOrder(obj)
            if(response.code!==200){            
              return
            }
            let data=response.data
            let shoppingCartList=that.props.shoppingCart.data.filter((item,index)=>{
              return item.num>0
            })
            let updateOrderVarietyList=[]
            shoppingCartList.forEach((item,index)=>{
              let objTo={}
              objTo.orderId=data
              objTo.varietyId=item.varietyId
              objTo.num=item.num
              if(item.norms){objTo.normsId=item.norms.id}
              else{objTo.normsId=-1}
              updateOrderVarietyList.push(objTo)
            })
            await http.addOrderVariety({orderVarietyList:updateOrderVarietyList})
            await http.addNewOrder()
            Taro.hideLoading()
            that.props.ClearShoppingAction()
            Taro.reLaunch({
              url: '/pages/orderSuccess/index?orderId='+data
            })
          }catch(e){
            Taro.showToast({
              title: '系统错误',
              icon: 'error',
              duration: 2000
            })
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
  render () {
    return (
      <View style={{height:'100vh'}}>
        <View style={{height:'90vh',overflowY:'auto',backgroundColor:'#f2f2f2'}}>
          <View style={{height:'20vh',backgroundColor:'#1989fa',padding:'40rpx'}}>
            <View style={{fontSize:'36rpx',fontWeight:'800',color:'#fff'}}>确定订单，提交订单</View>
            <View style={{fontSize:'30rpx',marginTop:'25rpx',color:'#fff'}}>菜品详情查看</View>
          </View>
          <View style={{minHeight:'70vh',position:'relative'}}>
            <View style={{
              position:'absolute',
              top:'-100rpx',
              left:'0'
            }}
            >
              <View style={{
                minHeight:'500rpx',
                width:'670rpx',
                backgroundColor:'#fff',
                margin:'0 40rpx 20rpx 40rpx',
                borderRadius:'15rpx'
              }}
              >
                {
                  this.props.shoppingCart.data.map((item2)=>{
                    return item2.num>0?<List key={item2.id} obj={item2} not></List>:null
                  })
                }
              </View>
              <View style={{
                width:'670rpx',
                backgroundColor:'#fff',
                margin:'0 40rpx 20rpx 40rpx',
                borderRadius:'15rpx'
              }}
              >
                <Field
                  label='备注(选填)'
                  placeholder='请根据口味偏好'
                  style={{borderRadius:'15rpx'}}
                  value={this.state.remarks}
                  onChange={(e)=>{
                    this.setState({remarks:e.detail})
                  }}
                />
                <Field
                  required
                  clearable
                  label='餐具份数'
                  value={this.state.num}
                  style={{borderRadius:'15rpx'}}
                />
              </View>
            </View>
          </View>
        </View>
        <View style={{height:'10vh',backgroundColor:'#fff',padding:'20rpx 30rpx'}}>
          <View style={{float:'right'}}>
            <Text>合计<Text style={{fontWeight:'600',fontSize:'40rpx'}}>￥{(this.props.shoppingCart.money*100)/100}</Text></Text>
            <Button type='info' round style={{marginLeft:'30rpx',width:'250rpx'}} onClick={this.submitClick}>提交订单</Button>
          </View>
        </View>
        <Loading></Loading>
      </View>
    )
  }
}
Index.defaultProps = {}
export default Index

